package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"order/api/request"
	"order/inter/dao"
	"order/inter/model"
)

func CreateCom(c *gin.Context) {
	var req request.CreateCom
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var com model.Commrnts
	dao.GetOneByFields(&model.Commrnts{Common: req.Common}, &com)
	if com.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "此账号不存在",
			"data": nil,
		})
		return
	}
	com = model.Commrnts{
		OrderId:   uint32(req.OrderId),
		ProductId: uint32(req.ProductId),
		Common:    req.Common,
	}
	if !dao.Create(&com) {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "评论添加失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": com,
	})
}

func FindCom(c *gin.Context) {
	var com []model.Commrnts
	dao.GetListByFields(&model.Commrnts{}, &com)

	var pros []*model.Commrnts
	for _, v := range com {
		pros = append(pros, &v)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": pros,
	})
}

func UpdateCom(c *gin.Context) {
	var req request.UpdateCom
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1000,
		"msg":  "验证失败",
		"data": dao.Update(&model.Commrnts{
			Id:        uint64(req.Id),
			OrderId:   uint32(req.OrderId),
			ProductId: uint32(req.ProductId),
			Common:    req.Common,
		}),
	})
}

func DelCom(c *gin.Context) {
	var req request.DelCom
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1000,
		"msg":  "验证失败",
		"data": dao.Delete(&model.Commrnts{
			Id: uint64(req.Id),
		}),
	})
}
